/*
 * 更新调拨表
 * 参数   交易码：trancode=61114
 * 
 */

package org.ccams.tran;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.ccams.domain.TMaterielStock;
import org.ccams.domain.TpMovbackD;
import org.ccams.domain.TpMovbackH;
import org.ccams.domain.User;
import org.ccams.web.UserSession;
import org.ccams.web.WebBeanFactory;
import org.json.JSONArray;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


public class Tran61114 extends AbstractJsonTran {

	@SuppressWarnings("unchecked")
	public void buildJSONObject(Map model, JSONObject json,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		TpMovbackH tmh = new TpMovbackH();
		
		Long num =Long.parseLong( request.getParameter("num"));//取得记录ID
		Date cw_date = null;
		try{
			cw_date=new SimpleDateFormat("y-M-d").parse(request.getParameter("cw_date"));
			System.out.println("财务日期:"+cw_date);
		}catch(Exception e){}
		
		int uid =  Integer.parseInt(request.getParameter("uid"));
		System.out.println("调拨部门:"+uid);
		
		int buid =  Integer.parseInt(request.getParameter("back_uid"));
		System.out.println("接收部门:"+buid);
		
		//获得制单人
		HttpSession session = request.getSession();
		UserSession userSession = (UserSession)session.getAttribute("userSession");
		User user = userSession.getUser();
//		String pname=user.getUserName();
		System.out.println("制单人:"+user.getUserName());
		
		tmh.setNum(num);
//		tmh.setPname(pname);
		tmh.setPid(user.getId());
		tmh.setCw_date(cw_date);
//		tmh.setUname(uname);
//		tmh.setBackuname(backuname);
		tmh.setUid(uid);
		tmh.setBack_uid(buid);
		tmh.setOperdate(new Date());
		
		//获得详细信息
		String params =  request.getParameter("detail");
		
		JSONArray detailParams = new JSONArray(params);
		
		HashMap<String, Object> jsonMap = new HashMap<String, Object>();
		String success = "";
		String message = "";	
		int k=0;		
		DataSourceTransactionManager txm = (DataSourceTransactionManager) WebBeanFactory.getBean("transactionManager",request);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txm.getTransaction(def);
		try{
			k = getCcamsService().getTpmovbackhDao().updateTpmovbackh(tmh);//更新调拨主表信息
			for(int i=0;i<detailParams.length();i++){
				org.json.JSONObject detail = detailParams.optJSONObject(i);
				TpMovbackD tmd = new TpMovbackD();
				tmd.setNum(num);
				tmd.setIdt_Materiel(detail.getLong("idt_Materiel"));
				tmd.setMaterielName(detail.getString("materielName"));
				tmd.setBatchno(detail.getString("batchno"));
				tmd.setFactcode(detail.getString("factcode"));
				tmd.setSerialNo(detail.getString("serialNo"));
				try{
					tmd.setProd_date(new SimpleDateFormat("y-M-d").parse(detail.getString("prod_date")));
				}catch(Exception e){}
				try{
					tmd.setEnd_date(new SimpleDateFormat("y-M-d").parse(detail.getString("end_date")));
				}catch(Exception e){}
				tmd.setBatchid(detail.getInt("batchid"));
				tmd.setAmount(detail.getLong("amount"));
				tmd.setBack_price(detail.getDouble("back_price"));
				tmd.setCause(detail.getString("cause"));
				tmd.setKind(Short.parseShort(detail.getString("kind")));
				
				System.out.println("=================================");
				System.out.println("单据ID 	:	" +tmd.getNum());			
				System.out.println("物料名称 	:	" +tmd.getMaterielName());			
				System.out.println("批号 	:	" +tmd.getBatchno());			
				System.out.println("厂家条码 	:	" +tmd.getFactcode());			
				System.out.println("机身码 	:	" +tmd.getSerialNo());			
				System.out.println("生产日期 	:	" +tmd.getProd_date());			
				System.out.println("有效期 	:	" +tmd.getEnd_date());			
				System.out.println("批次 	:	" +tmd.getBatchid());			
				System.out.println("调出数量 	:	" +tmd.getAmount());			
				System.out.println("调出价格 	:	" +tmd.getBack_price());			
				System.out.println("调出原因 	:	" +tmd.getCause());			
				System.out.println("单据类型	:	" +tmd.getKind());			
				boolean b = detail.has("ord");
				if(b){
					tmd.setOrd(Integer.parseInt(detail.getString("ord")));
					k = getCcamsService().getTpmovbackdDao().updateTpmovbackd(tmd);//执行更新
				}else{
					int ord = getCcamsService().getTpmovbackdDao().getNewOrd(num);
					tmd.setOrd(ord);
					k = getCcamsService().getTpmovbackdDao().insertTpmovbackd(tmd);//执行添加	
				}
				if(k==1){ 
					TMaterielStock tms = new TMaterielStock();
//					tms.setUname(uname);
					tms.setUid(uid);
//					tms.setMaterielName(detail.getString("materielName"));
					tms.setIdt_materiel(detail.getLong("idt_Materiel"));
					int idt = getCcamsService().getTmaterielstockDao().getIdtStock(tms);
					if(idt==0){//库存中没有此物料记录信息
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "部门库存中无此物料<"+tmd.getMaterielName()+">的相关记录");
						json.putAll(jsonMap);
						return;
					}
					int stockAmount = getCcamsService().getTmaterielstockDao().getStockAmount(tms);//取得库存数量
					if(stockAmount < tmd.getAmount()){//进行数量判断
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "物料<"+tmd.getMaterielName()+">的库存不足");
						json.putAll(jsonMap);
						return;
					}
				}
			}
		}
		catch(Exception ex){
			txm.rollback(status);
	        ex.printStackTrace();
		}
		txm.commit(status);
		
		if (k == 1) {
			success = "true";
			message = "调拨更新成功";
		} else {
			success = "false";
			message = "调拨更新失败";
		}
		jsonMap.put("success", success);
		jsonMap.put("message", message);
		json.putAll(jsonMap);
	}
}
